"""
    Controller for all mass actions in mnemoply project.
    Anyone action has a special unique URL and it avaible by this URL.
    See `make_mass_action_url` function.
"""

import turbogears, cherrypy
from turbogears import expose, identity, validate
from mnemoply.controllers.containers import Container
from mnemoply.mass_actions import registry
from mnemoply.error_handling import handle_std_exceptions
from mnemoply.utils import ExceptionsBunch

def make_mass_action_url(class_name, name):
    return '/MassActions/%s-%s/' % (class_name, name)

class MassActionsController(Container):
    search_in_object = True

    def _check_access(self, action):
        """
            Check permission like `MassActionClass/action_name`.
            Point of interest.
        """

        if not action.read_only:
            if not identity.has_any_permission('dba',
                '%s/%s' % (action.target_class.getModelName(), action.name)):
                raise identity.IdentityFailure([])

    def _get_item(self, name):
        try:
            class_name, action_name = name.split('-', 1)
            action = registry.actions[class_name][action_name]
            self._check_access(action)

            return action
        except KeyError:
            return None

    @handle_std_exceptions()
    @expose()
    def call(self, action, **kw):
        try:
            if not kw.get("referer", ''):
                kw['referer'] = cherrypy.request.headerMap['Referer']
        except KeyError:
            raise cherrypy.NotFound()

        @validate(form=action.form)
        def validated_call(action, tg_errors=None, **args):
            if tg_errors is not None:
                return dict(
                    tg_template="genshi:mnemoply.templates.lib.mass_action_params",
                    action=action,
                    ma_url=make_mass_action_url(
                        action.target_class.__name__,
                        action.name
                    )
                )

            # Convert ID's into objects
            objs = [action.target_class.get(id) for id in args.pop('ids')]

            referer = args.pop('referer')

            ret = action.call(objs, **args)
            if ret is None:
                # Redirect back we came from
                if action.flash_message:
                    turbogears.flash(action.flash_message)
                else:
                    flash_string = _('Mass action "%s" is successfully executed') % action.title
                    if not action.successfully_execute:
                        flash_string = _('Mass action "%s" isn\'t successfully executed') % action.title
                    turbogears.flash(flash_string)
                raise turbogears.redirect(referer)
            else:
                return ret

        return validated_call(action, **kw)
    call.expose_object = True

    show = call

exposed = MassActionsController()
